package com.jd.after.modules.mis.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jd.after.common.core.R;
import com.jd.after.modules.mis.entity.Blog;
import com.jd.after.modules.mis.entity.Category;
import com.jd.after.modules.mis.service.BlogService;
import com.jd.after.modules.mis.service.CategoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @RestController：返回json
 * 
 * @PostMapping
 * @GetMapping
 * 
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    // 注入
    @Autowired
    CategoryService categoryService;
    @Autowired
    BlogService blogService;

    /**
     * 获取 树形结构数据
     * 
     * @return
     */
    @PostMapping("/list")
    public R list() {

        List<Category> entityList = categoryService.list(new QueryWrapper<Category>().orderByAsc("order_num"));

        Map<Long, Category> entityMap = new HashMap<>();
        List<Category> resultList = new ArrayList<>();

        // 将List转换成Map 当然用java8 流也可以，这里用for比较清晰。
        for (Category entity : entityList) {
            entity.setChildren(new ArrayList<>());
            entityMap.put(entity.getId(), entity);
        }

        // 组装成数结构列表
        for (Category entity : entityList) {
            Category parentEntity = entityMap.get(entity.getPid());
            // 如果查询出的列表里面该节点的没有父节点说明是顶级节点
            if (parentEntity == null) {
                // 将顶级节点加入结果集中
                resultList.add(entity);
                continue;
            }
            // 把自己加到父节点对象里面去
            parentEntity.getChildren().add(entity);
        }

        return R.ok(resultList);
    }

    /**
     * 信息
     * 
     * /info/3 ==>get
     * 
     * @PathVariable
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        Category entity = categoryService.getById(id);
        return R.ok(entity);
    }

    @PostMapping("/save")
    public R save(@Validated @RequestBody Category entity) {
        categoryService.save(entity);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@Validated @RequestBody Category entity) {

        // 1.判断是否移动到自身子目录下 path 1,2,3 pid 3 id 4 => path: *,4,*
        if (!entity.getPath().isEmpty()
                && Arrays.asList(entity.getPath().split(",")).contains(entity.getId().toString())) {
            return R.error("不能移动到自身目录下");
        }

        categoryService.updateById(entity);
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id) {
        // 根据业务

        // 1.首先判断是否有子目录，提醒 select * from ca where pid=？
        List<Category> childs = categoryService.list(new QueryWrapper<Category>().eq("pid", id));
        if (childs != null && childs.size() > 0)
            return R.error("当前目录非空，请先删除子目录");

        // 2.判断当前目录是否被使用
        List<Blog> blogs = blogService.list(new QueryWrapper<Blog>().eq("c_id", id));
        if (blogs != null && blogs.size() > 0)
            return R.error("当前目录下有博客内容，请先删除博客");

        categoryService.removeById(id);
        return R.ok();
    }

}
